using System;
using Android.Text;
using Android.Text.Style;
using Android.Util;
using Android.Content;
using Android.Views;
using Android.Widget;

namespace jivemessenger
{
    public class LinkTextView : TextView
    {
        public LinkTextView(Context context,IAttributeSet attr) :
            base(context,attr)
        {

        }



        public override bool OnTouchEvent(MotionEvent e)
        {
            TextView widget = (TextView) this;
            Object text = widget.Text;
            if (text.GetType()==typeof(SpannableString)) {
                SpannableString buffer = (SpannableString) text;

                //  int action = e.ActionIndex;

                if (e.Action == MotionEventActions.Up
                    || e.Action == MotionEventActions.Down) {
                        int x = (int)e.RawX;
                        int y = (int) e.RawY;

                        x -= widget.PaddingLeft;
                        y -= widget.PaddingTop;

                        x += widget.ScrollX;
                        y += widget.ScrollY;

                        Layout layout = widget.Layout;
                        int line = layout.GetLineForVertical(y);
                        int off = layout.GetOffsetForHorizontal(line, x);

                        ClickableSpan[] link = (ClickableSpan[])buffer.GetSpans(off, off, Java.Lang.Class.FromType(typeof(StyleSpan)));

                        if (link.Length != 0) {
                            if (e.Action ==  MotionEventActions.Up) {
                                link[0].OnClick(widget);
                            } else if (e.Action ==  MotionEventActions.Down) {
                                Selection.SetSelection(buffer,
                                                       buffer.GetSpanStart(link[0]),
                                                       buffer.GetSpanEnd(link[0]));
                            }
                            return true;
                        }
                    }

            }

            return false;
        }
    }
}